package org.dh2580.delay.queue.bean.executor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hao.deng
 * @Date: 2019/5/15-上午10:11
 */
public class SimpleScheduleExecutor {
    private ScheduledExecutorService scheduledExecutor;

    public SimpleScheduleExecutor(int threadSize, String poolNamePrefix) {
        scheduledExecutor = new ScheduledThreadPoolExecutor(threadSize, new SimpleThreadFactory(poolNamePrefix, true));
    }

    public void schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
        scheduledExecutor.schedule(runnable, delay, timeUnit);
    }

    public void scheduleAtFixedRate(Runnable runnable, long initDelay, long period, TimeUnit timeUnit) {
        scheduledExecutor.scheduleAtFixedRate(runnable, initDelay, period, timeUnit);
    }

    public void scheduleWithFixedDelay(Runnable runnable, long initDelay, long delay, TimeUnit timeUnit) {
        scheduledExecutor.scheduleWithFixedDelay(runnable, initDelay, delay, timeUnit);
    }

    public void shutdown() throws InterruptedException {
        scheduledExecutor.shutdown();
        while (!scheduledExecutor.awaitTermination(1, TimeUnit.SECONDS)) { }
    }

}
